package com.swp.oa.comomn;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.swp.oa.util.FileHelper;

/**
 * @brief  服务器配置选项类
 * @author lvly-design
 *
 */
public class Option {
	//配置文件
	private static final String CONFIG_FILE = "config.xml";
	//文件仓文件
	public static final String  LIBRARIAN_FILE = "librarian_file";
	//数据库文件
	public static final String LIBRARIAN_DATABASE = "librarian_database";
	// 虚拟文件仓类型
	private static String librarianType = ""; 
	// 文件仓URL
	private static String libraryUrl = ""; 
	// 本地文件仓, 根虚拟目录对应的物理路径
	private static String filePath = ""; 
	// svn仓库，暂时无用
	private static String svnPath = "";
	// 临时文件目录(结果)
	private static String temporary = "";
	// 缓存目录
	private static String cache = ""; 
	// 清空临时文件目录
	private static boolean clearTemporaryOnExit = false;	 
	
	private static List<String> IPs = new ArrayList<String>();
	
	private static String changePassWordCycle = "";
	
	// 加载配置文件
	static {
		String path = getConfigPath();
		loadConfigFile(path);
	}
	
	/**
	 * 获取仓库类型
	 * 
	 * @return 仓库类型
	 */
	public static String getLibrarianType() {
		return librarianType;
	}
	
	/**
	 * 设置仓库类型
	 * 
	 * @param librarianType 仓库类型
	 * @param save 是否保存到配置文件中
	 */
	public static void setLibrarianType(String librarianType, boolean save) {
		Option.librarianType = librarianType;
		
		if(save){ //判断是否保存到xml文件中
			String configPath = getConfigPath();
			saveConfigFile(configPath);   //保存到文件中
		}
	}

	/**
	 * 将路径中的“\”转换成url识别的"/"
	 * 
	 * @return the libraryUrl
	 */
	public static String getLibraryUrl() {
		return libraryUrl.replace('\\', '/');
	}

	/**
	 * 设置文件仓url
	 * 
	 * @param libraryUrl the libraryUrl to set
	 * @Param save 是否保存到文件中
	 */
	public static void setLibraryUrl(String libraryUrl, boolean save) {
		Option.libraryUrl = libraryUrl;
		
		if(save){ //判断是否保存
			
			//保存到文件中
			String configPath = getConfigPath();
			saveConfigFile(configPath);
		}
	}
	
	/**
	 * 将路径中的“\”转换成url识别的"/"
	 * 
	 * @return the filePath
	 */
	public static String getFilePath() {
//		filePath = "E:/tongyuan/works/configuration/Library";
		File file = new File(filePath);
		try {
			if(!file.exists()){
				FileHelper.createFile(filePath, true, true);	
			}
		} catch (Exception e) {
//			e.printStackTrace();
			filePath = "C:/tongyuan/works/configuration/Library";
		}
		return filePath.replace('\\', '/');
	}

	/**
	 * 设置文件路径
	 * 
	 * @param filePaththe filePath to set
	 * @param save 是否保存到配置文件中
	 */
	public static void setFilePath(String filePath, boolean save) {
		Option.filePath = filePath;
		
		if(save){  //判断是否保存
			
			//保存到文件中
			String configPath = getConfigPath();
			saveConfigFile(configPath);
		}
	}

	/**
	 * 将路径中的“\”转换成url识别的"/"
	 * 
	 * @return the svnPath
	 */
	public static String getSvnPath() {
		return svnPath.replace('\\', '/');
	}

	/**
	 * 设置svn路径
	 * 
	 * @param svnPath the svnPath to set
	 * @param save 是否保存到配置文件中
	 */
	public static void setSvnPath(String svnPath, boolean save) {
		Option.svnPath = svnPath;
		
		if(save){  //判断师父保存
			
			//保存到文件中
			String configPath = getConfigPath();
			saveConfigFile(configPath);
		}
	}

	/**
	 * 获取临时文件目录
	 * 
	 * @return the temporary
	 */
	public static String getTemporary() {
		return temporary;
	}

	/**
	 * 设置临时文件目录
	 * 
	 * @param temporary the temporary to set
	 * @param 是否保存到配置文件中
	 */
	public static void setTemporary(String temporary, boolean save) {
		Option.temporary = temporary;
		
		if(save){ //判断是否保存
			
			// 保存到文件中
			String configPath = getConfigPath();
			saveConfigFile(configPath);
		}
	}
	
	/**
	 * 获取缓冲目录
	 * 
	 * @return 缓冲目录
	 */
	public static String getCache() {
		File file = new File(cache);
		try {
			if(!file.exists()){
				FileHelper.createFile(cache, true, true);	
			}
		} catch (Exception e) {
//			e.printStackTrace();
			cache = "C:/tongyuan/works/configuration/Library/Cache";
		}
		return cache;
	}

	/**
	 * 设置缓冲目录
	 * 
	 * @param cache 缓冲目录
	 * @param save 是否保存到配置文件中
	 */
	public static void setCache(String cache, boolean save) {
		Option.cache = cache;
		
		if(save){ //判断是否保存
			
			//保存到xml文件
			String configPath = getConfigPath();
			saveConfigFile(configPath);
		}
	}

	/**
	 * 是否清空临时目录
	 * 
	 * @return clearTemporaryOnExit
	 */
	public static boolean isClearTemporaryOnExit() {
		return clearTemporaryOnExit;
	}

	/**
	 * 设置清空临时目录
	 * 
	 * @param clearTemporaryOnExit 是否清空临时目录
	 * @param save 是否保存
	 */
	public static void setClearTemporaryOnExit(boolean clearTemporaryOnExit,boolean save) {
		Option.clearTemporaryOnExit = clearTemporaryOnExit;
		
		if(save){
			String configPath = getConfigPath();
			saveConfigFile(configPath);
		}
	}
	
	public static List<String> getIPs() {
		return IPs;
	}

	public static Integer getChangePassWordCycle() {
		if(changePassWordCycle != null && !changePassWordCycle.equals("")){
			return Integer.parseInt(changePassWordCycle);
		}else{
			return 30;			
		}
	}

	/**
	 * 加载config.xml文件
	 * 
	 * @param path	文件全名
	 * @return true=加载成功
	 */
	public static boolean loadConfigFile(String path){
		
		SAXReader saxReader = new SAXReader();
		
		File file = new File(path);  //打开文件

		Document doc = null;
		try {
			//读取配置文件构造dom
			doc = saxReader.read(file);  
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		
		//获取根节点
		Element root = doc.getRootElement();
		
		//获取文件仓类型
		Element typeElem = root.element("Librarian").element("Type");
		if(typeElem != null){
			librarianType = typeElem.getText();			
		}
		//获取文件仓url
		Element urlElem = root.element("Librarian").element("LibraryUrl");
		if(urlElem != null){
			libraryUrl = urlElem.getText();			
		}
		
		//判断filepath节点是否存在
		Element filePathElem = root.element("Librarian").element("FilePath");
		if(filePathElem != null){
			//获取文件路径
			filePath = filePathElem.getText();
		}
		
		//判断svnpath节点是否存在
		Element svnPathElem = root.element("Librarian").element("SvnPath");
		if (svnPathElem != null) {
			//获取svn仓库路径
			svnPath = svnPathElem.getText();
		}
		//获取临时文件目录
		Element temporaryElem = root.element("Temporary");
		if(temporaryElem != null){
			temporary = temporaryElem.getTextTrim();			
		}
		//获取缓冲区目录
		Element cacheElem = root.element("Cache");
		if(cacheElem != null){
			cache = cacheElem.getTextTrim();			
		}
		
		//获取清理临时目录标志
		Element clearTemporaryOnExitElem = root.element("ClearTemporaryOnExit");
		if(clearTemporaryOnExitElem != null){
			clearTemporaryOnExit = Boolean.parseBoolean(clearTemporaryOnExitElem.getText());			
		}
		
		List<Element> elemIps = root.element("AllowedIps").elements();
		if(elemIps != null){
				for (Element e : elemIps) {
					IPs.add(e.getTextTrim());
				}		
		}
		
		Element changePassWordCycleElem = root.element("ChangePassWordCycle");
		if(changePassWordCycleElem != null){
			changePassWordCycle = changePassWordCycleElem.getText();			
		}
		
		return true;
	}

	/**
	 * 将配置写入config.xml
	 * 
	 * @param path	文件全名
	 * @return	true=写入成功
	 */
	private static boolean saveConfigFile(String path){
		
		// 写入到DOC中
		Document doc = DocumentHelper.createDocument();
		Element eltRoot = DocumentHelper.createElement("Config");
		doc.setRootElement(eltRoot);
		
		//添加子元素Librarian
		Element eltLibrarian = eltRoot.addElement("Librarian");
		
		Element eltUrl = eltLibrarian.addElement("LibraryUrl");		//添加url
		eltUrl.setText(libraryUrl);
		
		Element eltFilePath = eltLibrarian.addElement("FilePath");		//添加FilePath
		eltFilePath.setText(filePath);
		
		Element eltSvnPath = eltLibrarian.addElement("SvnPath");		//添加 SvnPath
		eltSvnPath.setText(svnPath);
		
		//添加元素Temporary
		Element eltTemporary = eltRoot.addElement("Temporary");
		eltTemporary.setText(temporary);
		
		// 添加元素cache
		Element eltCache = eltRoot.addElement("Cache");
		eltCache.setText(cache);
		
		//添加元素ClearTemporaryOnExit
		Element eltClearTemporaryOnExit = eltRoot.addElement("ClearTemporaryOnExit");
		eltClearTemporaryOnExit.setText(String.valueOf(clearTemporaryOnExit));
		
		XMLWriter xmlWriter = null;
		//写入到文件
		try {
			xmlWriter = new XMLWriter(new java.io.FileOutputStream(new File(path)));
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		try {
			xmlWriter.write(doc);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return true;
	}
	
	/**
	 * 获取配置文件路径
	 * 
	 * @return 配置文件路径
	 */
	public static String getConfigPath(){
		String path = null;
		String configPath = null;
		try {
//			path = Option.class.getClassLoader().getResource("/").toURI().getPath();
			path = Option.class.getClassLoader().getResource("").getPath();
//			System.out.println("path: " + path);
			File file = new File(path);
			configPath = file.getPath() + "\\" + CONFIG_FILE ;
		} catch (Exception e1) {
			e1.printStackTrace();
		}
//		String configPath = path + CONFIG_FILE;
//		System.out.println(configPath);
		return configPath;
	}
	
} // end class
